import { IApi } from "umi";
import { dirname } from "path";
import { resolve } from "@umijs/utils";

function resolveProjectDep(opts: { pkg: any; cwd: string; dep: string }) {
  if (
    opts.pkg.dependencies?.[opts.dep] ||
    opts.pkg.devDependencies?.[opts.dep]
  ) {
    return dirname(
      resolve.sync(`${opts.dep}/package.json`, {
        basedir: opts.cwd,
      })
    );
  }
}
export default (api: IApi) => {
  api.modifyBabelPresetOpts((memo) => {
    memo.presetReact = {
      runtime: "automatic",
      importSource: "inulajs", // 新增
    };
    return memo;
  });
  api.modifyDefaultConfig((memo: any) => {
    const inulaPath =
      resolveProjectDep({
        pkg: api.pkg,
        cwd: api.cwd,
        dep: "inulajs",
      }) || dirname(require.resolve("inulajs/package.json"));
    memo.alias.react = inulaPath;
    memo.alias.inulajs = inulaPath;
    memo.alias["react-dom"] = inulaPath;
    // react-dom/client 顺序要在 react-dom 之前
    if (memo.alias["react-dom/client"]) {
      memo.alias["react-dom/client"] = inulaPath;
    } else {
      memo.alias = {
        "react-dom/client": inulaPath,
        ...memo.alias,
      };
    }
    return memo;
  });
};
